<template>
  <el-container>
    <el-header>
      <el-divider content-position="left"><span style="font-size: 14px">当前选择角色：</span>

          <el-select v-model="value" size="mini" placeholder="请选择">
            <el-option
              v-for="i in options"
              :key="i.id"
              :label="i.name"
              :value="i.id"
              >
            </el-option>
          </el-select>
        <el-button style="margin-left: 10px;" v-permission="'Save'" type="success" size="mini" icon="el-icon-finished" @click="onSubmit">保存</el-button>
        <el-button style="float: right;" size="mini" icon="el-icon-refresh-right" circle @click="reloadTable"></el-button>
      </el-divider>
    </el-header>
    <el-container>
      <el-aside width="25%" style="background: #ffffff;">
        <el-form ref="form" :model="form" label-width="80px">
          <el-row>
            <el-col>
          <el-form-item label="数据权限">
            <el-select v-model="form.data_range" placeholder="请选择数据权限">
              <el-option
                v-for="item in dataOptions"
                :key="item.index"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
            </el-col>
          </el-row>
        </el-form>
              <div v-show="form.data_range === 4">
                <el-tree
                  :data="deptOptions"
                  show-checkbox
                  default-expand-all
                  :default-checked-keys="deptCheckedKeys"
                  ref="dept"
                  node-key="id"
                  :props="defaultProps"
                ></el-tree>
              </div>
      </el-aside>


      <el-main style="padding-top: 0px;">
        <el-tree
          :data="tableData"
          show-checkbox
          v-loading="loading"
          default-expand-all
          node-key="id"
          :expand-on-click-node="false"
          :default-checked-keys='defaultCheckNode'
          ref="menuTree"
          highlight-current
          :check-on-click-node="true"
          style="width: 100%;"
          :props="defaultProps">
         <span class="custom-tree-node" slot-scope="{node,data}">
           <span>{{data.name}}</span>
          <el-checkbox
            v-for="item in data.menuPermission"
            :key="item.index"
            v-model="item.checked"
            style="padding-left: 30px;"
            >
            {{ item.name }}</el-checkbox>
          </span>
        </el-tree>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
  import { getRoleData,GetMenuDataByid,editRoleData,getRoleDataById } from '@/api/role'
  import { getDeptData } from '@/api/dept'
  import { getMenuData } from '@/api/menu'
  import { successMsg } from '@/utils/tools'
  import insert from '../menu/insert'
  import edit from '../menu/edit'

  export default {
    name:'RolePermission',
    components:{
      insert,
      edit
    },
    mounted() {
      this.fetchMenuData()
      this.getSelectFunc()
      this.getDeptFunc()
    },
    data() {
      return {
        title:this.$route.params.title,
        role_id:this.$route.params.id,
        deptCheckedKeys:[],
        rolePermission:[],
        deptOptions:[],
        loading:false,
        form:{
          name:'',
          key:'',
          data_range:''
        },
        options: [],
        dataOptions:[{
          name:'仅本人数据权限',
          value:0
        },{
          name:'本部门及以下数据权限',
          value:1
        },{
          name:'本部门数据权限',
          value:2
        },{
          name:'全部数据权限',
          value:3
        },{
          name:'自定数据权限',
          value:4
        }],
        value: this.$route.params.id,
        defaultCheckNode:[],
        tableData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        params:{
          limit:999,
          id:this.$route.params.id
        }
      }
    },
    watch:{
      value:{
        immediate:true,
        handler(value){
          this.getCheckNodeFunc() /*察觉变化执行方法，查询该角色下所有权限*/
          this.getCheckBoxFunc(value)
        }
      }
    },
    methods:{
      fetchMenuData(){
        getMenuData().then(res=>{
          this.tableData=this.$utils.toArrayTree(res.data.data,{ parentKey: 'parent', strict: true })
          // this.buttonPer = res.data.data.menuPermission
        })
      },
      getSelectFunc(){
        getRoleData({'limit':999,'status':'True'}).then(res=>{
          this.options=res.data.data
        })
      },
      getDeptFunc(){
        getDeptData().then(res=>{
          this.deptOptions=this.$utils.toArrayTree(res.data.data,{ parentKey: 'parent', strict: true })
        })
      },
      getCheckNodeFunc(){
        getRoleDataById(this.value).then(res=>{
            this.deptCheckedKeys = res.data.dept
            this.defaultCheckNode=res.data.menu
            this.form.data_range = res.data.data_range
            this.form.name = res.data.name
            this.form.key = res.data.key
            this.rolePermission=res.data.permission
        })
      },
      getCheckBoxFunc(value){
        this.loading=true
        GetMenuDataByid(value).then(res => {
          res.data.data.forEach(x => {
            // 根据当前角色的permission,对menuPermisson进行勾选处理
            x.menuPermission.forEach(a => {
              if (this.rolePermission.indexOf(a.id) > -1) {
                this.$set(a, 'checked', true)
              } else {
                this.$set(a, 'checked', false)
              }
            })
          })
          setTimeout(() => {
            this.tableData=this.$utils.toArrayTree(res.data.data,{ parentKey: 'parent', strict: true })
            this.loading=false;
          }, 1000);
        })
      },
      // 所有勾选菜单节点数据
      getMenuAllCheckedKeys () {
        // 目前被选中的菜单节点
        const checkedKeys = this.$refs.menuTree.getCheckedKeys()
        // 半选中的菜单节点
        const halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys()
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
        return checkedKeys
      },
      // 所有自定义权限时,勾选的部门节点数据
      getDeptAllCheckedKeys () {
        // 目前被选中的部门节点
        const checkedKeys = this.$refs.dept.getCheckedKeys()
        // 半选中的部门节点
        // const halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys()
        // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
        return checkedKeys
      },
      onSubmit(){
        const params={}
        params['id'] = this.value
        params['data_range'] = this.form.data_range
        params['key'] = this.form.key
        params['name'] = this.form.name
        params['menu'] = this.getMenuAllCheckedKeys() // 获取选中的菜单
        params['dept'] = this.getDeptAllCheckedKeys() // 获取选中的部门
        const menuData = this.$utils.toTreeArray(this.tableData)
        const permissionData = []
        menuData.forEach(x => {
          const checkedPermission = x.menuPermission.filter(f => {
            return f.checked
          })

          if (checkedPermission.length > 0) {
            for (const item of checkedPermission) {
              permissionData.push(item.id)
            }
          }
        })
        params['permission'] = permissionData
        editRoleData(params).then(res=>{
          if(res.code===2000) {
            successMsg(res.msg)
            this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
            this.$router.push(this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.length - 1].path)
          }else{
            errorMsg(res.msg)
          }
        })
      },
      reloadTable(){

      }
    }
  }
</script>
<style>
  .div_padding {
    padding: 10px 10px
  }
  .custom-tree-node {
    flex: 1;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
